/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.ronsicecream.pos.mk.transaction.receiptfromwarehouse;

import com.ronsicecream.pos.out.transaction.receiptfromwh.*;
import com.buanalintas.bynga.Action;
import com.buanalintas.bynga.Controller;
import com.buanalintas.bynga.Field;
import com.buanalintas.bynga.Logger;
import com.buanalintas.bynga.Page;
import com.buanalintas.bynga.Persistence;
import com.buanalintas.bynga.Sequence;
import com.buanalintas.bynga.Utility;
import com.buanalintas.bynga.formatter.DateFormatter;
import com.ronsicecream.pos.entities.PosMasterItemStock;
import com.ronsicecream.pos.entities.PosMasterStatus;
import com.ronsicecream.pos.entities.PosMasterUnit;
import com.ronsicecream.pos.entities.PosTransactionItemStock;
import com.ronsicecream.pos.entities.PosTransactionOutReceiptMaterialFromWarehouse;
import com.ronsicecream.pos.entities.PosTransactionOutReceiptMaterialFromWarehouseDetail;
import com.ronsicecream.pos.entities.PosTransactionWhDistributionToOutlet;
import com.ronsicecream.pos.entities.PosTransactionWhDistributionToOutletDetail;
import com.ronsicecream.pos.master.item.Item;
import com.ronsicecream.pos.master.status.Status;
import com.ronsicecream.pos.out.transaction.receiptfromwhdetail.ReceiptDetail;
import java.math.BigDecimal;
import java.util.Calendar;
import java.util.List;
import javax.persistence.EntityManager;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author user
 */
public class Receipt extends Page {

    private Field receiptId;
    private Field receiptDate;
    private Field receiptNumber;
    private Field receiptTotal;
    private Field receiptQuantity;
    private Field receiptPaid;
    private Field receiptUnpaid;
    private Field receiptKeel;
    private Field receiptDescription;
    private Field receiptTimestamp;
    private Field receiptDistributionId;
//    private Field receiptSupplierId;
    private Field receiptRegionalId;
    private Field receiptUserId;
    private Field receiptUnitId;

    public Receipt() {
        super();

        setTheClass(PosTransactionOutReceiptMaterialFromWarehouse.class);
        setPageDetail(ReceiptDetail.class);

        receiptId = new Field();
        receiptId.setName("receiptId");
        receiptId.setCaption("id");
        receiptId.setListProperties("");
        receiptId.setInputProperties("");
        getFields().add(receiptId);

        receiptNumber = new Field();
        receiptNumber.setName("receiptNumber");
        receiptNumber.setCaption("number");
        receiptNumber.setListProperties(" align=\"center\" width=\"15%\" nowrap");
        receiptNumber.setInputProperties(" size=\"30\" readonly");
        receiptNumber.setRequired(true);
        getFields().add(receiptNumber);

        receiptUnitId = new Field();
        receiptUnitId.setName("receiptUnitId");
        receiptUnitId.setCaption("unit");
        receiptUnitId.setListProperties(" align=\"center\" width=\"15%\" nowrap");
        receiptUnitId.setInputProperties("");
        getFields().add(receiptUnitId);

//        receiptSupplierId = new Field();
//        receiptSupplierId.setName("receiptSupplierId");
//        receiptSupplierId.setCaption("supplier");
//        receiptSupplierId.setListProperties(" width=\"10%\" nowrap");
//        receiptSupplierId.setInputProperties(" size=\"30\" ");
//        receiptSupplierId.setRequired(true);
//        receiptSupplierId.getSelectorColumns().add(new String[]{"supplierCode", " Code", "width=\"30%\" nowrap"});
//        receiptSupplierId.getSelectorColumns().add(new String[]{"supplierName", " Name", "width=\"50%\""});
//        receiptSupplierId.getSelectorColumns().add(new String[]{"supplierPhone", " Phone", "align=\"center\" width=\"20%\" nowrap"});
//        getFields().add(receiptSupplierId);

        receiptRegionalId = new Field();
        receiptRegionalId.setName("receiptRegionalId");
        receiptRegionalId.setCaption("regional");
        receiptRegionalId.setListProperties(" width=\"10%\" nowrap");
        receiptRegionalId.setInputProperties(" size=\"30\" ");
        receiptRegionalId.setRequired(true);
        receiptRegionalId.getSelectorColumns().add(new String[]{"regionalCode", " Code", "width=\"30%\" nowrap"});
        receiptRegionalId.getSelectorColumns().add(new String[]{"regionalName", " Name", "width=\"50%\""});
        getFields().add(receiptRegionalId);

        receiptDistributionId = new Field();
        receiptDistributionId.setName("receiptDistributionId");
        receiptDistributionId.setCaption("distribution");
        receiptDistributionId.setRequired(true);
        receiptDistributionId.setSelectorLoad(true);
        receiptDistributionId.setSelectorCondition("t.distributionUnsent >0");
        receiptDistributionId.getSelectorColumns().add(new String[]{"distributionNumber", "Number", "width=\"20%\" nowrap"});
//        receiptDistributionId.getSelectorColumns().add(new String[]{"workOrderNumber", "Number", "width=\"20%\""});
//        receiptWoId.getSelectorColumns().add(new String[]{"workOrdernTotal", " Total", " align=\"right\" width=\"10%\" nowrap"});
        receiptDistributionId.getSelectorColumns().add(new String[]{"distributionUnsent", " Unsent", " align=\"right\" width=\"10%\" nowrap"});
        receiptDistributionId.getSelectorColumns().add(new String[]{"distributionDescription", " Description", "width=\"40%\""});
        receiptDistributionId.setSelectorOrder("t.distributionNumber");
        receiptDistributionId.setListProperties(" align=\"left\" width=\"15%\" nowrap");
        receiptDistributionId.setInputProperties(" size=\"20\"");
        getFields().add(receiptDistributionId);

        receiptQuantity = new Field();
        receiptQuantity.setName("receiptQuantity");
        receiptQuantity.setCaption("total quantity");
        receiptQuantity.setListProperties(" align=\"right\" width=\"8%\" nowrap");
        receiptQuantity.setInputProperties(" size=\"8\" readonly");
        getFields().add(receiptQuantity);

        receiptDate = new Field();
        receiptDate.setName("receiptDate");
        receiptDate.setCaption("date");
        receiptDate.setListProperties(" align=\"center\" width=\"6%\" nowrap");
        receiptDate.setInputProperties(" size=\"8\" readonly");
        receiptDate.setDefaultValue(Utility.getTimestamp());
        getFields().add(receiptDate);

        receiptTotal = new Field();
        receiptTotal.setName("receiptTotal");
        receiptTotal.setCaption("total");
        receiptTotal.setListProperties(" align=\"right\" width=\"8%\" nowrap");
        receiptTotal.setInputProperties(" size=\"8\"");
        receiptTotal.setRequired(true);
//        receiptTotal.setFormater(MoneyFormatter.getInstance());
        getFields().add(receiptTotal);

        receiptPaid = new Field();
        receiptPaid.setName("receiptPaid");
        receiptPaid.setCaption("paid");
        receiptPaid.setListProperties(" align=\"right\" width=\"8%\" nowrap");
        receiptPaid.setInputProperties(" size=\"8\"");
        receiptPaid.setRequired(true);
//        receiptPaid.setFormater(MoneyFormatter.getInstance());
        getFields().add(receiptPaid);

        receiptUnpaid = new Field();
        receiptUnpaid.setName("receiptUnpaid");
        receiptUnpaid.setCaption("unpaid");
        receiptUnpaid.setListProperties(" align=\"right\" width=\"8%\" nowrap");
        receiptUnpaid.setInputProperties(" size=\"8\"");
        receiptUnpaid.setRequired(true);
//        receiptPaid.setFormater(MoneyFormatter.getInstance());
        getFields().add(receiptUnpaid);

        receiptKeel = new Field();
        receiptKeel.setName("receiptKeel");
        receiptKeel.setCaption("keel");
        receiptKeel.setListProperties(" align=\"center\" width=\"5%\" nowrap");
        receiptKeel.setInputProperties(" ");
        receiptKeel.getOptions().add(new String[]{"1", "NO"});
        receiptKeel.getOptions().add(new String[]{"2", "YES"});
        getFields().add(receiptKeel);

        receiptTimestamp = new Field();
        receiptTimestamp.setName("receiptTimestamp");
        receiptTimestamp.setCaption("timestamp");
        receiptTimestamp.setListProperties(" align=\"center\" width=\"1%\" nowrap");
        receiptTimestamp.setInputProperties(" size=\"12\"");
        getFields().add(receiptTimestamp);

        receiptDescription = new Field();
        receiptDescription.setName("receiptDescription");
        receiptDescription.setCaption("description");
        receiptDescription.setListProperties(" width=\"70%\"");
        receiptDescription.setInputProperties(" cols=\"50\" rows=\"5\"");
        receiptDescription.setInputType(Field.INPUT_TEXT_AREA);
        receiptDescription.setInputCase(Field.CASE_UPPER);
        getFields().add(receiptDescription);

        getActions().add(Action.TRANS_ADD);
        getActions().add(Action.TRANS_EDIT);
        getActions().add(Action.TRANS_VIEW);

        fillFields();

        getFieldsAdd().clear();
        getFieldsAdd().add(receiptNumber);
        getFieldsAdd().add(receiptDistributionId);
        getFieldsAdd().add(receiptDate);
        getFieldsAdd().add(receiptDescription);

        getFieldsEdit().clear();
        getFieldsEdit().add(receiptNumber);
        getFieldsEdit().add(receiptDistributionId);
        getFieldsEdit().add(receiptDate);
        getFieldsEdit().add(receiptDescription);

        getFieldsList().clear();
        getFieldsList().add(receiptNumber);
        getFieldsList().add(receiptDistributionId);
//        getFieldsList().add(receiptSupplierId);
        getFieldsList().add(receiptDate);
        getFieldsList().add(receiptQuantity);
        getFieldsList().add(receiptTotal);
        getFieldsList().add(receiptPaid);
        getFieldsList().add(receiptUnpaid);
        getFieldsList().add(receiptKeel);
        getFieldsList().add(receiptDescription);

        getFieldsView().clear();
        getFieldsView().add(receiptDate);
        getFieldsView().add(receiptNumber);
        getFieldsView().add(receiptQuantity);
//        getFieldsView().add(receiptSupplierId);
        getFieldsView().add(receiptTotal);
        getFieldsView().add(receiptPaid);
        getFieldsView().add(receiptUnpaid);
        getFieldsView().add(receiptKeel);
        getFieldsView().add(receiptDescription);
        getFieldsView().add(receiptDistributionId);
        getFieldsView().add(receiptTimestamp);

        setController(new Receipt.ReceiptWHController(this));
        getController().setOrder(receiptTimestamp);
        getController().setOrderType(Controller.ORDER_DESC);

    }

    @Override
    public void beforeList() {
        if (!getCurrentUnit().getUnitId().equals(1)) {
            getController().setCondition("t.receiptUnitId.unitId=" + getCurrentUnit().getUnitId());
        }
    }

    @Override
    public void afterInit(HttpServletRequest req, HttpServletResponse res) {
        receiptDate.setFormater(DateFormatter.getInstanceDate(this));
        receiptTimestamp.setFormater(DateFormatter.getInstanceDateTime(this));
    }

    @Override
    public void beforeAdd() {
        receiptNumber.setDefaultValue(generate());
    }

    public String generate() {
        String unitCode = (getCurrentUnit()).getUnitCode();
        Calendar cal = Calendar.getInstance();
        String year = "" + cal.get(Calendar.YEAR);
        String month = Utility.intToRoman(cal.get(Calendar.MONTH) + 1);
        try {
            PosTransactionOutReceiptMaterialFromWarehouse rec = (PosTransactionOutReceiptMaterialFromWarehouse) getEntityManager().createQuery("SELECT t FROM PosTransactionOutReceiptMaterialFromWarehouse t "
                    + "WHERE t.receiptNumber LIKE '%/" + unitCode + "/RecFromWarehouse/%/" + year + "' "
                    + "ORDER BY t.receiptTimestamp DESC").setHint(Persistence.REFRESH_HINT, true).setFirstResult(0).setMaxResults(1).getSingleResult();
            return Utility.lpad(Integer.parseInt(rec.getReceiptNumber().substring(0, 4)) + 1, 4, "0") + "/" + unitCode + "/RecFromWarehouse/" + month + "/" + year;
        } catch (Exception e) {
        }
        return "0001/" + unitCode + "/RecFromWarehouse/" + month + "/" + year;
    }

    class ReceiptWHController extends Controller {

        public ReceiptWHController(Page page) {
            super(page);
            setOrder("receiptTimestamp");
            setOrderType("DESC");
        }

        @Override
        public void beforeInsert(Object data, List list) {
            PosTransactionOutReceiptMaterialFromWarehouse receipt = (PosTransactionOutReceiptMaterialFromWarehouse) data;
            EntityManager em = getEntityManager();
            receipt.setReceiptNumber(generate());
            receipt.setReceiptUnitId(getCurrentUnit());
            receipt.setReceiptUserId(getCurrentUser());
            receipt.setReceiptTimestamp(Utility.getTimestamp());
            receipt.setReceiptDate(Utility.getFirstDate());
            receipt.setReceiptKeel("1");
            receipt.setReceiptPaid(BigDecimal.ZERO);
        }

        @Override
        public void afterInsert(Object data, List list) {

            EntityManager em = getEntityManager();
            PosMasterStatus statusGood = Status.getStatusGood(em);
            try {
                em.getTransaction().begin();
                PosTransactionOutReceiptMaterialFromWarehouse receipt = (PosTransactionOutReceiptMaterialFromWarehouse) data;
                PosTransactionWhDistributionToOutlet distribution = receipt.getReceiptDistributionId();

//                receipt.setReceiptSupplierId(po.getPurchaseOrderSupplierId());
//                receipt.setReceiptRegionalId(po.getPurchaseOrderRegionalId());
//                System.out.println("receipt regional :"+receipt.getReceiptRegionalId() + " po regional :"+po.getPurchaseOrderRegionalId());
//                receipt.setReceiptPosUnitId(po.getPurchaseOrderPosUnitId());
//                System.out.println(" supplier ya disini :"+receipt.getReceiptSupplierId()+" posUnit :"+receipt.getReceiptPosUnitId());
//                receipt.setReceiptRegionalId(po.getPurchaseOrderRegionalId());
//                System.out.println(" regional ya disini :"+receipt.getReceiptRegionalId());

                 PosMasterUnit posunit = (PosMasterUnit) em.createQuery("SELECT t FROM PosMasterUnit t"
                            + " WHERE t.unitUnitTypeId.unitTypeId=3 "
                            + " AND t.unitUnitId.unitId=" + getCurrentUnit().getUnitId()                       
      
                            )
                            .setHint(Persistence.REFRESH_HINT, true).getSingleResult();
                    System.out.println("unittt :" + posunit + " unit name: " + posunit.getUnitName());
                    receipt.setReceiptPosUnitId(posunit);
                    receipt.setReceiptRegionalId(posunit.getUnitRegionalId());
                    System.out.println("Pos Unit :" + receipt.getReceiptPosUnitId() + " dan reguler :" + receipt.getReceiptRegionalId());

                
                BigDecimal total = BigDecimal.ZERO;
                BigDecimal totalQuantity = BigDecimal.ZERO;
                for (Object detail : list) {
                    PosTransactionOutReceiptMaterialFromWarehouseDetail receiptDetail = (PosTransactionOutReceiptMaterialFromWarehouseDetail) detail;

                    PosTransactionWhDistributionToOutletDetail poDetail = (PosTransactionWhDistributionToOutletDetail) em.createQuery("SELECT t FROM PosTransactionWhDistributionToOutletDetail t"
                            + " WHERE t.distributionDetailItemId.itemId=" + receiptDetail.getReceiptDetailItemId().getItemId()
                            //                            + " AND t.purchaseOrderDetailSatuanId.satuanId="+receiptDetail.getReceiptDetailSatuanId().getSatuanId()
                            + " AND t.distributionDetailDistributionId.distributionId=" + distribution.getDistributionId())
                            .setHint(Persistence.REFRESH_HINT, true).getSingleResult();
                    System.out.println(" poDetail ya disini :" + poDetail + " >>po:" + distribution.getDistributionId());
                    poDetail.setDistributionDetailSent(poDetail.getDistributionDetailSent().add(receiptDetail.getReceiptDetailQuantity()));
                    poDetail.setDistributionDetailUnsent(poDetail.getDistributionDetailUnsent().subtract(receiptDetail.getReceiptDetailQuantity()));

                    PosMasterItemStock stockItem = Item.getStockItem(em, receiptDetail.getReceiptDetailItemId(), getCurrentUnit());
                    PosTransactionItemStock item = new PosTransactionItemStock();

                    item.setItemStockId(Sequence.next(item));
                    item.setItemStockItemId(receiptDetail.getReceiptDetailItemId());
                    item.setItemStockRegionalId(posunit.getUnitRegionalId());
                    item.setItemStockPosUnitId(posunit);
//                            item.setItemStockStatusId(statusGood);
                    item.setItemStockType("9");
                    item.setItemStockLast(stockItem.getItemStockValue());
                    item.setItemStockValue(receiptDetail.getReceiptDetailQuantity());
                    item.setItemStockCurrent(stockItem.getItemStockValue().add(item.getItemStockValue()));
                    item.setItemStockUnitId(getCurrentUnit());
                    item.setItemStockUserId(getCurrentUser());
                    item.setItemStockTimestamp(Utility.getTimestamp());
                    em.persist(item);
                    stockItem.setItemStockValue(item.getItemStockCurrent());
                    stockItem.setItemStockTimestamp(receipt.getReceiptTimestamp());

                    total = total.add(receiptDetail.getReceiptDetailPrice().multiply(receiptDetail.getReceiptDetailQuantity()));
                    totalQuantity = totalQuantity.add(receiptDetail.getReceiptDetailQuantity());
                }
                System.out.println(" Totalnya disini :" + total);
                System.out.println(" Quantitynya disini :" + totalQuantity);
                receipt.setReceiptTotal(total);
                receipt.setReceiptQuantity(totalQuantity);
                receipt.setReceiptUnpaid(total);

                distribution.setDistributionUnsent(distribution.getDistributionUnsent().subtract(totalQuantity));
                distribution.setDistributionSent(distribution.getDistributionSent().add(totalQuantity));
                System.out.println(" Tessss ");
                em.getTransaction().commit();
            } catch (Exception e) {
                Logger.getInstance().log(e);
                System.out.println(" Erorrnya disini :" + e);
            }
        }
    }
}
